<template>
    <div  style="overflow-y:hidden;">
        <div ref="scroll" @mouseover="tableMouseOver" @mouseout="tableMouseout">
            <div>
                <!--:scroll-x="{gt: 10}"
                :scroll-y="{gt: 100}"-->
                <vxe-table
                        v-loading.iTable="showLoading"
                        :data="data"
                        :stripe="true"
                        ref="scrollTable"
                        :height="height"
                        :tooltip-config="{contentMethod: showTooltipMethod, enterable: true,theme:effect,
                        delayHover:10000}"
                        :highlight-current-row="true"
                        @checkbox-change="select"
                        @checkbox-all="selectAll"
                        @row-click="rowClick"
                        border
                        resizable
                        show-overflow
                        highlight-hover-row
                        show-header-overflow
                        :row-style="getRowStyle"
                        :tree-props="{children: 'children'}"
                        :tree-config="treeConfig"
                        header-row-class-name="tableHeader"
                        class="commonVxeTable"
                        :checkbox-config="{checkMethod:checkMethod}"
                        show-overflow-tooltip="true"
                        @scroll="tableScrollFunc"
                        :autoResize="autoResize"
                        style="width: 100%">
                    <vxe-table-column v-if="mutiSelect" type="selection" width="60px" align="center">
                    </vxe-table-column>
                    <!--region 按钮操作组-->
                    <vxe-table-column v-if="operates&&(operates.align=='left')" title="操作" align="center"
                                      :fixed="operates.fixed?'left':null"
                                      :width="operates.width">
                        <template slot-scope="scope">
                            <div class="operate-group">
                                <template v-for="(btn, key) in operates.list">
                                    <div class="item"
                                         v-if="btn.show !== false && (btn.isShow == undefined || btn.isShow(scope.row))"
                                         :key='btn.id'>
                                        <template v-if="btn.cls">
                                            <el-tooltip class="item" :effect="effect" :content="btn.label" placement="top" :openDelay="1000">
                                                <image-button :cls="btn.cls" :disabled="btn.disabled"
                                                              @click.stop="btn.method(key,scope.row)">
                                                </image-button>
                                            </el-tooltip>
                                        </template>
                                        <template v-else>
                                            <inner-button :type="btn.type" size="mini" :icon="btn.icon"
                                                          :disabled="btn.disabled"
                                                          :text="btn.label"
                                                          :plain="btn.plain" @click.stop="btn.method(key,scope.row)">
                                            </inner-button>
                                        </template>
                                    </div>
                                </template>
                            </div>
                        </template>
                    </vxe-table-column>
                    <!--endregion-->
                    <vxe-table-column type="expand" show-overflow-tooltip="false" width="50" title="内容" v-if="isExpand">
                        <template slot-scope="scope">
                            <p class="expandRow" v-html="scope.row[expandColumn]">

                            </p>
                        </template>
                    </vxe-table-column>
                    <template v-for="(column, index) in columns">
                        <vxe-table-column :field="column.propertyName"
                                          :visible="!column.hidden"
                                          :key='column.propertyName'
                                          :title="column.caption"
                                          :fixed="column.fixed"
                                          :align="column.textAlignment"
                                          :sortable="systemSort&&column.allowSort"
                                          :show-overflow-tooltip="true"
                                          :min-width="column.minWidth"
                                          :tree-node="column.tree"
                                          :width="column.width">
                            <template slot-scope="scope">
                                <template v-if="!column.render">
                                    <template v-if="column.formatter">
                                        <common-tooltip :tip="column.formatter(scope.row,column)">
                                            <span v-html="column.formatter(scope.row,column)"></span>
                                        </common-tooltip>
                                    </template>
                                    <template v-else >
                                        <common-tooltip :tip="scope.row[(column.propertyName||column.fieldName)]">
                                            <span v-html="scope.row[(column.propertyName||column.fieldName)]"></span>
                                        </common-tooltip>
                                    </template>
                                </template>
                                <template v-else>
                                    <expand-dom :column="column" :row="scope.row" :render="column.render"
                                                :index="index"></expand-dom>
                                </template>
                            </template>
                        </vxe-table-column>
                    </template>
                    <!--region 按钮操作组-->
                    <vxe-table-column v-if="operates&&(operates.align == undefined || operates.align=='right')" title="操作"
                                      align="center" :fixed="''+operates.fixed?'right':'false'"
                                      :width="operates.width">
                        <template slot-scope="scope">
                            <div class="operate-group">
                                <template v-for="(btn, key) in operates.list">
                                    <div class="item"
                                         v-if="btn.show !== false && (btn.isShow == undefined || btn.isShow(scope.row))"
                                         :key='btn.id'>
                                        <template v-if="btn.cls">

                                            <el-tooltip class="item" :effect="effect" :content="btn.label" placement="top" :openDelay="1000">
                                                <image-button :cls="btn.cls" :disabled="btn.disabled"
                                                              @click.stop="btn.method(key,scope.row)">
                                                </image-button>
                                            </el-tooltip>
                                        </template>
                                        <template v-else>
                                            <inner-button :type="btn.type" size="mini" :icon="btn.icon"
                                                          :disabled="btn.disabled"
                                                          :text="btn.label"
                                                          :plain="btn.plain" @click.stop="btn.method(key,scope.row)">
                                            </inner-button>
                                        </template>
                                    </div>
                                </template>
                            </div>
                        </template>
                    </vxe-table-column>
                    <!--endregion-->
                </vxe-table>
                <div @click="getData" v-if="!noMore" style="background: #fff;text-align: center;cursor:pointer;">
                    加载更多...
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    import Service from '../../../services/common.service'

    export default {
        data() {
            const me = this;
            return {
                data: [],
                checkedRecordList: [],
                total: 0,
                page: 1,
                parameters: me.params,
                loading: false,
                scrollloading: false,
                showLoading: false,
                systemSort: true,
                preTime:0,
                mouseScroll:true,
            }
        },
        components: {
            expandDom: {
                functional: true,
                props: {
                    row: Object,
                    render: Function,
                    index: Number,
                    column: {
                        type: Object,
                        default: null
                    }
                },
                render: (h, ctx) => {
                    const params = {
                        row: ctx.props.row,
                        index: ctx.props.index
                    }
                    if (ctx.props.column) params.column = ctx.props.column
                    return ctx.props.render(h, params)
                }
            }
        },
        watch: {
            params(val) {
                this.setParameters(val)
            }
        },
        computed: {
            noMore() {
                let r = this.total < (this.page - 1) * this.pageSize;
                if(this.data.length ==0){
                    return true;
                }
                return r;
            },
            busy() {
                return this.scrollloading || this.noMore
            }
        },
        mounted() {

        },
        created: function () {
            this.page = 1;
            if (window.localStorage.getItem("systemSetting")) {
                let settings = JSON.parse(window.localStorage.getItem("systemSetting"));
                let showSort = settings['ui.table.column.header.showSort'] == undefined ? true : settings['ui.table.column.header.showSort'];
                this.systemSort = (showSort == false || ('' + showSort).toUpperCase() == 'FALSE') ? false : true;
            }
        },
        methods: {
            reset() {
                const me = this;
                me.page = 1;
                me.data = [];
                me.scrollloading = false;
                setTimeout(function(){
                    me.getData()
                },50);
            },
            setParameters(val) {
                const me = this;
                me.parameters = val;
                if (me.autoPost) {
                    me.reset();
                }
            },
            scrollFunc(e) {
                const me = this;
                console.log(me.treeConfig)
                if(!me.treeConfig){
                    return;
                }
                me.mouseScroll = true;
                let scroll = this.$refs.scroll;
                if (scroll.getElementsByClassName("vxe-table--body-wrapper").length == 0
                    || scroll.getElementsByClassName("vxe-table--body").length == 0) {
                    return;
                }

                let currentTime = new Date().getTime();
                if(currentTime - me.preTime <200 ||  me.showLoading ){
                    return;
                }

                me.preTime = currentTime;

                if (scroll.getElementsByClassName("vxe-table--body")[0].scrollHeight <= (scroll.getElementsByClassName("vxe-table--body-wrapper")[0].scrollTop+scroll.offsetHeight+100)
                    && e.deltaY >= 100) {
                    setTimeout(function(){
                        me.getData();
                    },10)
                }
            },

            tableScrollFunc(e ) {
                const me = this;
                if(me.mouseScroll){
                    return;
                }
                if(!me.treeConfig){
                    return;
                }
                let scroll = this.$refs.scroll;
                if (scroll.getElementsByClassName("vxe-table--body-wrapper").length == 0
                    || scroll.getElementsByClassName("vxe-table--body").length == 0) {
                    return;
                }

                let currentTime = new Date().getTime();
                if(currentTime - me.preTime <20 ||  me.showLoading ){
                    return;
                }

                me.preTime = currentTime;

                if (scroll.getElementsByClassName("vxe-table--body")[0].scrollHeight <= e.scrollTop+scroll.offsetHeight+100){
                    setTimeout(function(){
                        me.getData();
                    },10)
                }
            },
            firstLoadData(){
                let scroll = this.$refs.scroll;
                if (scroll.getElementsByClassName("vxe-table--body")[0].scrollHeight < scroll.offsetHeight) {
                    this.getData();
                }
            },
            tableMouseOver(e) {
                if (document.addEventListener) {
                    document.addEventListener('DOMMouseScroll', this.scrollFunc, false);
                }//W3C
                window.onmousewheel = document.onmousewheel = this.scrollFunc;//IE/Opera/Chrome
            },
            tableMouseout(e) {
                if (document.removeEventListener) {
                    document.removeEventListener('DOMMouseScroll', this.scrollFunc, false);
                }//W3C
                window.onmousewheel = document.onmousewheel = function () {

                };//IE/Opera/Chrome
            },
            handleSelectionChange(val) {
                this.multipleSelection = val

                this.$emit('selection-change', this.$refs['table'].selection)
            },
            /*select(selection,row){
                if(selection.indexOf(row) == -1){
                    this.$refs['table'].toggleRowSelection(row, false);
                    if (row.children) {
                        for (let r of row.children) {
                            this.$refs['table'].toggleRowSelection(r, false)
                        }
                    }
                }else{
                    this.$refs['table'].toggleRowSelection(row, true);
                    if (row.children) {
                        for (let r of row.children) {
                            this.$refs['table'].toggleRowSelection(r, true)
                        }
                    }
                }
            },
            selectAll(selection) {
                console.log(selection)
                let filter = selection.filter(item => {
                    return item.PARENTID == '0' || item.PARENTID == 0 || item.RANK == 3;
                })
                if (filter.length == 0) {
                    this.$refs['table'].clearSelection();
                }else{
                    for(let r of selection) {
                        if (r.children) {
                            for (let row of r.children) {
                                this.$refs['table'].toggleRowSelection(row, true)
                            }
                        }
                    }
                }
            },*/
            //全选事件
            selectAll ({ checked, records }) {
                this.$emit('selectAll', checked, records);
                this.$emit('selection-change', records)
                this.checkedRecordList = records;
            },
            // 单选事件
            select ({ checked, records }) {
                this.$emit('select', checked, records);
                this.$emit('selection-change', records)
                this.checkedRecordList = records;
            },
            rowClick(row, column, event) {
                this.$emit('rowClick', row, column, event)
            },

            getData() {
                const me = this;
                if (me.scrollloading) {
                    return;
                }
                let r = this.total < (this.page - 1) * this.pageSize;
                if (r) {
                    me.scrollloading = true;
                    let scroll = this.$refs.scroll;
                    if (scroll.getElementsByClassName("vxe-table--body-wrapper")[0].scrollTop > 0) {
                        this['$message']({
                            message: '所有数据加载完毕！',
                            type: 'succeed'
                        });
                    }
                    return;
                }
                me.parameters['page'] = me.page;
                me.parameters['pageSize'] = me.pageSize;
                me.scrollloading = true;
                me.showLoading = true;

                Service.post(me.url, me.parameters).then((res) => {
                    /* setTimeout(function () {
                        me.scrollloading = false;
                        me.showLoading = false;
                    }, 2000);*/
                    if (res.data.succeeded == true) {
                        let resData = res.data.data;
                        if (me.convertType == 'default') {
                            me.data = me.convertTree(me.data, resData);
                        } else if (me.convertType == 'custom' && me.convertChildren) {
                            me.data = me.convertChildren(me.data, resData);
                        } else {
                            me.data = me.data.concat(resData);
                        }
                        me.total = res.data.totalRecords;
                        /*const scrollTable = this.$refs.scrollTable
                        const startTime = Date.now()
                        if (scrollTable) {
                            this.$refs.scrollTable.reloadData(me.data).then(() => {
                                this.$XModal.message({ message: `渲染 ${ me.data.length} 行，用时 ${Date.now() - startTime}毫秒`, status: 'info' })
                                this.showLoading = false
                            })
                        }*/

                        me.$emit('afterLoad', me.total);
                        me.page++;
                        setTimeout(function() {
                            me.firstLoadData();
                            if (me.checkedRecordList.length > 0) {
                                let temp = [];
                                for (let checkRecord of me.checkedRecordList) {
                                    for (let i = 0; i < me.data.length; i++) {
                                        if(checkRecord.id == me.data[i].id
                                        && checkRecord.fondCode == me.data[i].fondCode
                                        && checkRecord.libId == me.data[i].libId){
                                            temp.push(me.data[i]);
                                            break;
                                        }
                                    }
                                }
                                me.$refs.scrollTable.setCheckboxRow(temp, true)
//                                me.$refs.scrollTable.setAllCheckboxRow(true)
                            }
                            if(me.isExpand) {
                                me.$refs.scrollTable.setAllRowExpansion(true);
                            }
                        },100);
                    } else {
                        me.data = [];
                        me.total = 0;
                    }
                    me.$nextTick(() => {
                        me.showLoading = false;
                        me.scrollloading = false;
                        me.mouseScroll = false;
                    });
                });
            },

            convertTree(allData,newData) {
                const me = this;
                let tempData = JSON.parse(JSON.stringify(allData));
                for (let j = 0; j < newData.length; j++) {
                    if(newData[j].RANK === 3 || !newData[j].PARENTID || '0' == newData[j].PARENTID){
                        tempData.push(newData[j]);
                    }
                }
                for (let j = 0; j < newData.length; j++) {
                    let hasParent = false;
                    for (let i = 0; i < tempData.length; i++) {
                        if (me.isChildren(tempData[i], newData[j])) {
                            hasParent = true;
                            if (!tempData[i].children) {
                                tempData[i].children = [];
                            }
                            tempData[i].children.push(newData[j]);
                            break;
                        }
                    }
                    if(!hasParent && newData[j].RANK === 4 && newData[j].PARENTID && newData[j].PARENTID !=='0'){
                        tempData.push(newData[j]);
                    }
                }
                return tempData;
            },

            isChildren(parent,child) {
                let a = child.PARENTID;
                let b = child.kindId;
                let c = child.partitionCode;
                let d = child.KIND_ID;
                if (!a) {
                    return false;
                }
                if (a == parent.id
                    && parent.RANK === 3
                    && parent.partitionCode == c
                    && parent.KIND_ID == d) {
                    return true;
                }
                return false;
            },
            checkMethod:function ({row}) {
                if (!this.allowCheckEmptyNode && row && row.RANK == 3 && (!row.children || row.children.length == 0)) {
                    return false;
                }
                if (row && row.canElectricBorrow === false && row.canPhysicalBorrow === false && row.reason) {
                    return false;
                }
                return true;
            },
            // 重写默认的提示内容
            showTooltipMethod({type, column, row, items, _columnIndex}) {
                // 重写默认的提示内容
//                console.log(column)
//                if (!column.property || column.property == this.expandColumn) {
                if(column.type == 'expand'){
                    return '';
                } else if (!this.allowCheckEmptyNode && column.type == 'selection' && row && row.RANK == 3 && (!row.children || row.children.length == 0)) {
                    return '该案卷没有查到符合条件的卷内文件,无法借阅!';
                } else if (column.type == 'selection' &&row && row.canElectricBorrow === false && row.canPhysicalBorrow === false && row.reason) {
                    return row.reason;
                }
            },
            getRowStyle:function(row){
                if(row.row.RANK == 3){
                    return 'background:#E1F5F9';
                }

            }
        },

        props: {
            /*data: {
                type: Array,
                default: function () {
                    return [];
                }
            },*/

            columns: {
                type: Array,
                default: () => []
            },

            operates: {},

            mutiSelect: false,

            height: Number,

            url: String,

            params: {
                type: Object,
                default: () => {
                }
            },

            autoPost: {
                type: Boolean,
                default: false
            },
            rowKey: {
                type: [String,Function],
                default: 'id'
            },
            convertType:{
                type: String,
                default: 'default' //none:不转化;default:默认规则转化;custom:传入转化函数,搭配convertChildren参数使用
            },
            convertChildren: {// 转化函数，参数1：现有数据集；参数2：新增数据集
                type: Function,
            },
            rowClassName:{
                type: [String,Function],
            },
            autoResize: {
                type:Boolean,
                default: true
            },
            isExpand:{
                type: Boolean,
                default:false
            },
            expandColumn:{
                type:String,
                default:'content'
            },
            effect:{
                type: String,
                default: 'dark'//light
            },
            allowCheckEmptyNode :{
                type: Boolean,
                default: true
            },
            treeConfig: {
                type: Object,Function,Boolean,
                default: ()=>{
                    return {children: 'children'};
                }
            },
            pageSize: {
                type: Number,
                default: 100
            },
        },
    }
</script>
<style lang="scss" scoped>
    /*.commonTable {
        margin-top: 3px;
        td, th{
            padding: 4px 0;
            text-align: center;
        }
        td{
            font-size: 0.875rem;
            color: #333;
        }
        .tableHeader th{
            background-color: #205193;
            color: #fff;
            padding: 5px 0;
            text-align: center;
            border-right: 1px solid #EBEEF5 !important;
        }
    }*/
</style>
